//
//  MQMusicMainViewController.m
//  MQ
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 徐永祥. All rights reserved.
//

#import "MQMusicMainViewController.h"
#import "MQMusicCell.h"
#import "PKRequestManager.h"
#import "MQMusicModel.h"
#import "MQMusicListViewController.h"
#import <MJRefresh.h>
#import "Reachability.h"
#import "MQPopupView.h"
#import "LewPopupViewAnimationDrop.h"
#import "MQChangeSkin.h"
@interface MQMusicMainViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;
@property (nonatomic, strong) NSMutableDictionary *parDic;

@end

@implementation MQMusicMainViewController
- (NSMutableArray *)dataSourceArr{
    if (_dataSourceArr == nil) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (void)requestData{
    self.parDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _parDic[@"resid"] = @"tj";
    _parDic[@"sid"] = @"244918960";
    _parDic[@"page"] = [NSString stringWithFormat:@"%ld", self.dataSourceArr.count / 10 + 1];
    _parDic[@"method"] = @"get_share_playlist";
    _parDic[@"imsi"] = @"460012676617727";
    _parDic[@"protocolCode"] = @"2.0";
    _parDic[@"size"] = @"10";
    _parDic[@"timestamp"] = @"20151028023014";
    _parDic[@"sign"] = @"ce576c7f5b7461aaa218145b43adaf24";
    
    [PKRequestManager requestWithType:POST urlString:@"http://client.ctmus.cn/iting2/imusic/V2" parDic:_parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
        for (NSDictionary *dic1 in dic[@"data"]) {
            MQMusicModel *model = [[MQMusicModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.dataSourceArr addObject:model];
            
        }
//        NSLog(@"---%@", dic);
//        NSLog(@"%ld", self.dataSourceArr.count);
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
    } error:^(NSError *error) {
        NSLog(@"解析失败 %@", [error localizedDescription]);
    }];
    
    
}

-(void)changeImage
{
    MQChangeSkin *view = [MQChangeSkin defaultPopupView];
    view.parentVC = self;
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationDrop new] dismissed:^{
        NSLog(@"动画结束");
        
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"音乐";
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"daohanglan"] forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(setting:)];
    //右上角设置按钮
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(setting:)];
    barButton.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = barButton;
//    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"一键换肤" style:(UIBarButtonItemStylePlain) target:self action:@selector(changeImage)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 30) / 2, (SCREEN_WIDTH - 30) / 2 + 30);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    
    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBarHidden = NO;
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString *picStr = [user valueForKey:@"picStr"];
    UIImageView *BigImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [BigImageView setImage:[UIImage imageNamed:picStr]];
    BigImageView.userInteractionEnabled = YES;
    [self.view addSubview:BigImageView];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 20, SCREEN_HEIGHT - 64) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[MQMusicCell class] forCellWithReuseIdentifier:@"musicCell"];
    [self.view addSubview:_collectionView];
    
    
    // 刷新数据
    __weak __typeof(self) weakSelf = self;
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf checkNetConnect];
    }];
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf checkNetConnect];
    }];
   
    [self checkNetConnect];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 判断网络连接
- (BOOL)checkNetConnect{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
        {
            NSLog(@"无网络");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:TITLE_MESSAGE preferredStyle:(UIAlertControllerStyleAlert)];
            
            [self presentViewController:alert animated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });
            
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
            return NO;
            
        }
            break;
            
        default:{
            //            _isData = YES;
            [self requestData];
            
            
        }
            break;
    }
    
    return YES;
    
}

#pragma mark UICollectionView的代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataSourceArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MQMusicCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"musicCell" forIndexPath:indexPath];
    MQMusicModel *model = self.dataSourceArr[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    [cell configureCellWithModel:model];

    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    MQMusicListViewController *musicListVC = [[MQMusicListViewController alloc] init];
    MQMusicModel *model = self.dataSourceArr[indexPath.row];
    musicListVC.myID = model.resid;
    musicListVC.title = model.songlistname;
    [self.navigationController pushViewController:musicListVC animated:YES];
    
}
//右上角设置按钮
- (void)setting:(UIBarButtonItem *)barButton
{
    MQPopupView *view = [MQPopupView defaultPopupView];
    view.parentVC = self;
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationDrop new] dismissed:^{
        NSLog(@"动画结束");
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
